import { syncSetTimeout, sendMessage, getMessage, dispatch } from "../../global/tools.js";

export default class Permission {
    static count = 0;
    constructor() {
        Permission.count++;
        if (Permission.count >= 2) {
            alert("collectionPlugin: \nError: Permission.count >= 2，即将刷新页面。");
            location.reload(true);
        } 
        this.config = {
            userPermission: "disabled",
            // 按照userPermission分配载入对象，getUserPermission()后，这个assignment会由对象变为一个列表，在其它地方直接处理array即可
            assignment: {}
        };
        this.init();
    } 
    init() {
    }
    async getUserPermission(userName) {
        return new Promise((resolve, reject) => {
            getMessage("anmi_permission", (message) => {
                switch (message.title) {
                    case "getUserPermission":
                        this.config.userPermission = message.data?.level || "disabled";
                        if ((this.config.userPermission === "admin") || (this.config.userPermission === "disabled")) {
                            this.config.assignment = [];
                        } else {
                            this.config.assignment = message.data?.assignment[this.config.userPermission];
                        }
                        resolve(this.config.userPermission);
                        break;
                    default:
                        break;
                }
            });
            sendMessage({
                from: "anmi_permission",
                to: "background",
                toUrl: "background",
                title: "getUserPermission",
                data: userName
            });
        });
    }
}